package com.qaml.mes.device.config;

import feign.Logger;
import feign.Request;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class FeignLogger extends Logger {

    @Override
    protected void log(String configKey, String format, Object... objects) {
        log.info(String.format(methodTag(configKey) + format, objects));
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        if (request.url().contains("mask/mail/message/send")) {
            return;
        }
        String requestMsg = request.httpMethod().name() + " " + request.url() + " HTTP/1.1";
        String bodyText = null;
        if (request.body() != null) {
            bodyText = request.charset() != null ? new String(request.body(), request.charset()) : "";
            log(configKey, "REQUEST【%s】,BODY【%s】", requestMsg, bodyText);
        }
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {

        try {
            Request request = response.request();
            String requestMsg = request.httpMethod().name() + " " + request.url() + " HTTP/1.1";
            String reposeBody = "";
            int status = response.status();
            if (response.body() != null && status != 204 && status != 205) {
                byte[] bodyData = Util.toByteArray(response.body().asInputStream());
                int bodyLength = bodyData.length;
                if (bodyLength > 0) {
                    reposeBody = Util.decodeOrDefault(bodyData, Util.UTF_8, "");
                }
                log(configKey, "REQUEST 【%s】, RESPONSE【%s】", requestMsg, reposeBody);
                return response.toBuilder().body(bodyData).build();
            }
        } catch (Exception e) {
            log(configKey, e.getMessage(), response);
        }
        return response;
    }
}
